use actix_web::body::BoxBody;
use actix_web::http::header::ContentType;
use actix_web::{get, web, App, Either, Error, HttpRequest, HttpResponse, HttpServer, Responder};
use serde::Serialize;
// use futures::{future::ok,stream::once};

#[derive(Serialize)]
struct MyObj {
    name: &'static str,
}

impl Responder for MyObj {
    type Body = BoxBody;

    fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> {
        let body = serde_json::to_string(&self).unwrap();
        HttpResponse::Ok()
            .content_type(ContentType::json())
            .body(body)
    }
}

async fn index() -> impl Responder {
    MyObj { name: "user" }
}

// 不知道once和ok是哪个依赖
// #[get("/stream")]
// async fn stream() -> HttpResponse {
//     let body = once(ok::<_, Error>(web::Bytes::from_static(b"test")));
//
//     HttpResponse::Ok()
//         .content_type("application/json")
//         .streaming(body)
// }

/// 使用Either可以返回两种类型其中之一
type RegisterResult = Either<HttpResponse, Result<&'static str, Error>>;

async fn index_2(b: web::Path<bool>) -> RegisterResult {
    if b.into_inner() {
        Either::Left(HttpResponse::BadRequest().body("Bad data"))
    } else {
        Either::Right(Ok("Hello"))
    }
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/", web::to(index))
            .route("/index_2/{bool}", web::to(index_2))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}
